import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

import '../controller.dart';
import '../../../../common/models/index.dart';

class VerificationPage extends GetView<MyIndexController> {
  const VerificationPage({Key? key}) : super(key: key);

  // 表单控制器
  static final _realNameController = TextEditingController();
  static final _idCardController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    // 确保控制器存在
    if (!Get.isRegistered<MyIndexController>()) {
      Get.put(MyIndexController());
    }
    
    // 页面初始化时查询认证状态
    WidgetsBinding.instance.addPostFrameCallback((_) {
      controller.checkAuthStatus();
    });
    
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text("实名认证"),
        centerTitle: true,
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 0,
        systemOverlayStyle: const SystemUiOverlayStyle(
          statusBarColor: Colors.transparent,
          statusBarIconBrightness: Brightness.dark,
        ),
      ),
      body: GetBuilder<MyIndexController>(
        builder: (controller) {
          return Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                // 认证状态显示
                Obx(() {
                  if (controller.authStatus != null) {
                    return Column(
                      children: [
                        _buildAuthStatusCard(controller.authStatus!),
                        const SizedBox(height: 20),
                      ],
                    );
                  }
                  return const SizedBox.shrink();
                }),
                
                // 证件类型
                _buildInfoRow("证件类型", "居民身份证"),
                
                const SizedBox(height: 20),
                
                // 真实姓名
                Obx(() {
                  final realNameAuth = controller.userService.currentUser?.extraData?['realNameAuth'];
                  final isVerified = realNameAuth != null && realNameAuth['verified'] == true;
                  final existingName = realNameAuth?['name'] ?? '';
                  
                  // 如果已认证，显示已有信息，否则显示输入框
                  if (isVerified && existingName.isNotEmpty) {
                    return _buildInfoRow("真实姓名", existingName, isInput: false);
                  } else {
                    return _buildInfoRow(
                      "真实姓名", 
                      "请输入真实姓名", 
                      isInput: true,
                      controller: _realNameController,
                    );
                  }
                }),
                
                const SizedBox(height: 20),
                
                // 证件号码
                Obx(() {
                  final realNameAuth = controller.userService.currentUser?.extraData?['realNameAuth'];
                  final isVerified = realNameAuth != null && realNameAuth['verified'] == true;
                  final existingIdCard = realNameAuth?['idCardNo'] ?? '';
                  
                  // 如果已认证，显示脱敏身份证号，否则显示输入框
                  if (isVerified && existingIdCard.isNotEmpty) {
                    return _buildInfoRow("证件号码", existingIdCard, isInput: false);
                  } else {
                    return _buildInfoRow(
                      "证件号码", 
                      "请输入身份证号码", 
                      isInput: true,
                      controller: _idCardController,
                      maxLength: 18,
                    );
                  }
                }),
                
                const SizedBox(height: 30),
                
                // 认证说明
                const Text(
                  "认证信息将用于玩真的平台服务,与账号唯一绑定,\n我们会对信息进行严格保密。",
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey,
                    height: 1.5,
                  ),
                  textAlign: TextAlign.center,
                ),
                
                const Spacer(),
                
                // 提交按钮
                Obx(() {
                  final realNameAuth = controller.userService.currentUser?.extraData?['realNameAuth'];
                  final isVerified = realNameAuth != null && realNameAuth['verified'] == true;
                  
                  // 如果已经认证，显示"已完成认证"按钮（禁用状态）
                  if (isVerified) {
                    return Container(
                      height: 50,
                      decoration: BoxDecoration(
                        color: Colors.green.withOpacity(0.3),
                        borderRadius: BorderRadius.circular(25),
                      ),
                      child: TextButton(
                        onPressed: null, // 禁用按钮
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(Icons.check_circle, color: Colors.green, size: 20),
                            const SizedBox(width: 8),
                            const Text(
                              "已完成认证",
                              style: TextStyle(
                                fontSize: 16,
                                color: Colors.green,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  }
                  
                  // 未认证时显示正常的提交按钮
                  return Container(
                    height: 50,
                    decoration: BoxDecoration(
                      color: controller.isSubmittingAuth 
                          ? Colors.grey[400] 
                          : const Color(0xFFFAE05E),
                      borderRadius: BorderRadius.circular(25),
                    ),
                    child: TextButton(
                      onPressed: controller.isSubmittingAuth 
                          ? null 
                          : () => _submitAuth(controller),
                      child: controller.isSubmittingAuth
                          ? const Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                SizedBox(
                                  width: 20,
                                  height: 20,
                                  child: CircularProgressIndicator(
                                    strokeWidth: 2,
                                    valueColor: AlwaysStoppedAnimation<Color>(Colors.black),
                                  ),
                                ),
                                SizedBox(width: 8),
                                Text(
                                  "提交中...",
                                  style: TextStyle(
                                    fontSize: 16,
                                    color: Colors.black,
                                  ),
                                ),
                              ],
                            )
                          : const Text(
                              "提交认证",
                              style: TextStyle(
                                fontSize: 16,
                                color: Colors.black,
                              ),
                            ),
                    ),
                  );
                }),
                
                const SizedBox(height: 20),
              ],
            ),
          );
        },
      ),
    );
  }
  
  // 构建信息行
  Widget _buildInfoRow(
    String label, 
    String value, {
    bool isInput = false,
    TextEditingController? controller,
    int? maxLength,
  }) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        SizedBox(
          width: 80,
          child: Text(
            label,
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.normal,
            ),
          ),
        ),
        Expanded(
          child: isInput
              ? TextField(
                  controller: controller,
                  maxLength: maxLength,
                  decoration: InputDecoration(
                    hintText: value,
                    hintStyle: const TextStyle(
                      fontSize: 16,
                      color: Colors.grey,
                    ),
                    border: InputBorder.none,
                    contentPadding: EdgeInsets.zero,
                    counterText: '', // 隐藏字符计数
                  ),
                  style: const TextStyle(
                    fontSize: 16,
                    color: Colors.black87,
                  ),
                )
              : Text(
                  value,
                  style: const TextStyle(
                    fontSize: 16,
                    color: Colors.black87,
                  ),
                ),
        ),
      ],
    );
  }

  // 构建认证状态卡片
  Widget _buildAuthStatusCard(RealnameAuthResponse authStatus) {
    Color statusColor;
    IconData statusIcon;
    String statusText;
    
    // 检查用户信息中的认证状态
    final userService = controller.userService;
    final realNameAuth = userService.currentUser?.extraData?['realNameAuth'];
    final isVerified = realNameAuth != null && realNameAuth['verified'] == true;
    
    print('🔍 认证页面状态检查:');
    print('  - authStatus.isVerified: ${authStatus.isVerified}');
    print('  - realNameAuth data: $realNameAuth');
    print('  - verified field: ${realNameAuth?['verified']}');
    print('  - final isVerified: $isVerified');
    
    if (isVerified) {
      statusColor = Colors.green;
      statusIcon = Icons.check_circle;
      statusText = '已认证';
    } else if (authStatus.data?.authStatus == 1) {
      statusColor = Colors.orange;
      statusIcon = Icons.access_time;
      statusText = '认证中';
    } else {
      statusColor = Colors.grey;
      statusIcon = Icons.info;
      statusText = '未认证';
    }

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: statusColor.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: statusColor.withOpacity(0.3)),
      ),
      child: Column(
        children: [
          Row(
            children: [
              Icon(statusIcon, color: statusColor, size: 24),
              const SizedBox(width: 8),
              Text(
                '认证状态：$statusText',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: statusColor,
                ),
              ),
            ],
          ),
          // 显示认证信息（优先从用户数据获取）
          if (isVerified && realNameAuth != null) ...[
            const SizedBox(height: 8),
            Row(
              children: [
                const Text(
                  '真实姓名：',
                  style: TextStyle(fontSize: 14, color: Colors.grey),
                ),
                Text(
                  realNameAuth['name'] ?? '',
                  style: const TextStyle(fontSize: 14, color: Colors.black87),
                ),
              ],
            ),
            const SizedBox(height: 4),
            Row(
              children: [
                const Text(
                  '身份证号：',
                  style: TextStyle(fontSize: 14, color: Colors.grey),
                ),
                Text(
                  realNameAuth['idCardNo'] ?? '',
                  style: const TextStyle(fontSize: 14, color: Colors.black87),
                ),
              ],
            ),
            const SizedBox(height: 4),
            Row(
              children: [
                const Text(
                  '认证时间：',
                  style: TextStyle(fontSize: 14, color: Colors.grey),
                ),
                Text(
                  _formatAuthTime(realNameAuth['authTime'] ?? ''),
                  style: const TextStyle(fontSize: 14, color: Colors.black87),
                ),
              ],
            ),
          ] else if (authStatus.maskedIdCard.isNotEmpty) ...[
            const SizedBox(height: 8),
            Row(
              children: [
                const Text(
                  '身份证号：',
                  style: TextStyle(fontSize: 14, color: Colors.grey),
                ),
                Text(
                  authStatus.maskedIdCard,
                  style: const TextStyle(fontSize: 14, color: Colors.black87),
                ),
              ],
            ),
          ],
          if (!isVerified && authStatus.authTime.isNotEmpty) ...[
            const SizedBox(height: 4),
            Row(
              children: [
                const Text(
                  '认证时间：',
                  style: TextStyle(fontSize: 14, color: Colors.grey),
                ),
                Text(
                  authStatus.authTime,
                  style: const TextStyle(fontSize: 14, color: Colors.black87),
                ),
              ],
            ),
          ],
        ],
      ),
    );
  }
  
  // 格式化认证时间
  String _formatAuthTime(String authTime) {
    if (authTime.isEmpty) return '';
    
    try {
      // 解析ISO时间格式：2025-07-16T23:40:01.643217
      final dateTime = DateTime.parse(authTime);
      return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
    } catch (e) {
      print('❌ 时间格式化失败: $e');
      return authTime; // 返回原始格式
    }
  }

  // 提交认证
  Future<void> _submitAuth(MyIndexController controller) async {
    final realName = _realNameController.text.trim();
    final idCard = _idCardController.text.trim();

    final success = await controller.submitRealnameAuth(
      realName: realName,
      idCardNo: idCard,
    );

    if (success) {
      // 🔥 修复：检查是否认证通过
      final realNameAuth = controller.userService.currentUser?.extraData?['realNameAuth'];
      final isVerified = realNameAuth != null && realNameAuth['verified'] == true;
      
      if (isVerified) {
        // 认证通过，立即返回上一页
        print('🎉 实名认证通过，立即返回');
        _realNameController.clear();
        _idCardController.clear();
        Get.back();
      } else {
        // 认证已提交但未通过，延迟返回
        print('📝 实名认证已提交，延迟返回');
        _realNameController.clear();
        _idCardController.clear();
        
        // 延迟返回上一页
        Future.delayed(const Duration(seconds: 2), () {
          if (Get.isDialogOpen == false && Get.isSnackbarOpen == false) {
            Get.back();
          }
        });
      }
    }
  }
} 